package com.ctjsoft.creation;

import java.util.concurrent.*;

/**
 * 测试使用-实现Callable接口的方式创建新线程
 *
 * @author: liaoyy
 * @date: Created in 2021/11/11 11:18
 */
public class CallableDemo implements Callable<String> {

    private String url;
    private String fileName;


    public CallableDemo(String url, String fileName) {
        this.url = url;
        this.fileName = fileName;
    }

    /**
     * 计算一个结果作为返回值
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    @Override
    public String call() throws Exception {
        WebDownLoader webDownLoader = new WebDownLoader();
        webDownLoader.downloader(url, fileName);
        System.out.println("download--" + fileName);
        return Thread.currentThread().getName() + "--下载成功！";
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CallableDemo callableDemo1 = new CallableDemo("https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png", "call1.jpg");
        CallableDemo callableDemo2 = new CallableDemo("https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png", "call2.jpg");
        CallableDemo callableDemo3 = new CallableDemo("https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png", "call3.jpg");
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        Future<String> submit1 = executorService.submit(callableDemo1);
        Future<String> submit2 = executorService.submit(callableDemo2);
        Future<String> submit3 = executorService.submit(callableDemo3);
        System.out.println(submit1.get());
        System.out.println(submit2.get());
        System.out.println(submit3.get());
        executorService.shutdown();
    }

}
